package com.renge.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.renge.commonutils.R;
import com.renge.eduservice.client.VodClient;
import com.renge.eduservice.entity.*;
import com.renge.eduservice.entity.json.CourseInfoJson;
import com.renge.eduservice.entity.json.CoursePublishJson;
import com.renge.eduservice.entity.json.FrontCourseInfo;
import com.renge.eduservice.entity.query.CourseQuery;
import com.renge.eduservice.entity.query.FrontCourseVo;
import com.renge.eduservice.mapper.EduCourseMapper;
import com.renge.eduservice.service.EduChapterService;
import com.renge.eduservice.service.EduCourseDescriptionService;
import com.renge.eduservice.service.EduCourseService;
import com.renge.eduservice.service.EduVideoService;
import com.renge.exception.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-06-04
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {
    @Autowired
    private EduCourseMapper eduCourseMapper;
    @Autowired
    private  EduCourseDescriptionService eduCourseDescriptionService;
    @Autowired
    private EduChapterService eduChapterService;
    @Autowired
    private EduVideoService eduVideoService;
    @Autowired
    private VodClient vodClient;
    //更新或者保存
    @Override
    @Transactional
    public String add(CourseInfoJson courseInfoJson) {
        //封装eduCourse并保存
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoJson,eduCourse);
        this.saveOrUpdate(eduCourse);
        String id = eduCourse.getId();
        //封装eduCourseDescription并保存
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setId(id);
        eduCourseDescription.setDescription(courseInfoJson.getDescription());
        eduCourseDescriptionService.saveOrUpdate(eduCourseDescription);
        return id;
    }
    //查询
    @Override
    public CourseInfoJson getCourseInfoJsonById(String id) {
        //查询Course
        EduCourse eduCourse = this.getById(id);
        if(eduCourse==null){
            return null;
        }
        //封装CourseInfoJson
        CourseInfoJson json = new CourseInfoJson();
        BeanUtils.copyProperties(eduCourse,json);
        EduCourseDescription courseDescription = eduCourseDescriptionService.getById(id);
        json.setDescription(courseDescription.getDescription());
        return json;
    }

    @Override
    public CoursePublishJson getCoursePublishJsonById(String id) {
        CoursePublishJson courseInformation = eduCourseMapper.getBasicCourseInformation(id);
        if(courseInformation!=null){
             return courseInformation;
        }
        return null;
    }

    @Override
    public IPage<EduCourse> pageCourseList(Page<EduCourse> page, QueryWrapper<EduCourse> wrapper, CourseQuery courseQuery) {
        if(courseQuery!=null&&!StringUtils.isEmpty(courseQuery.getTitle())){
            wrapper.like("title",courseQuery.getTitle());
        }
        if(courseQuery!=null&&!StringUtils.isEmpty(courseQuery.getStatus())){
            wrapper.eq("status",courseQuery.getStatus());
        }
        IPage<EduCourse> page1 = this.page(page, wrapper);
        return page1;
    }

    @Override
    @Transactional
    public void deleteById(String courseId) {
        //处理课程底下的章节
        QueryWrapper<EduChapter> chapterWrapper = new QueryWrapper<>();
        chapterWrapper.eq("course_id",courseId);
        List<EduChapter>  chapterlist = eduChapterService.list(chapterWrapper);
        if(chapterlist.size()>0){
            eduChapterService.remove(chapterWrapper);
        }
        //处理课程底下的小节
        QueryWrapper<EduVideo> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("course_id",courseId);
        List<EduVideo> videolist = eduVideoService.list(videoWrapper);
        if(videolist.size()>0){
            //处理小节的视频
            for(EduVideo v:videolist){
                String videoSourceId = v.getVideoSourceId();
                if(!StringUtils.isEmpty(videoSourceId)){
                    R r = vodClient.deleteVideoById(videoSourceId);
                    //判断是否调用回调方法
                    if(r.getCode()==20001){
                        GuliException guliException = new GuliException();
                        guliException.setMsg("该课程没有视频，地址存在错误");
                        throw guliException;
                    }
                }
            }
            eduVideoService.remove(videoWrapper);

        }
        eduCourseDescriptionService.removeById(courseId);
        this.removeById(courseId);
    }
    //返回首页八个热门课程
    @Override
    public List<EduCourse> IndexfindCourse() {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("view_count");
        wrapper.last("LIMIT 8");
        List<EduCourse> list = this.list(wrapper);
        return list;
    }
    //前端课程展示
    @Override
    public Map<String, Object> findFrontAllByPage(Integer curr, Integer pagesize, FrontCourseVo frontCourseVo) {
        //条件查询
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(frontCourseVo)){
            //最新时间
            if(!StringUtils.isEmpty(frontCourseVo.getGmtCreate())&&"1".equals(frontCourseVo.getGmtCreate())){
                wrapper.orderByDesc("gmt_create");
            }
            //价格排序
            if(!StringUtils.isEmpty(frontCourseVo.getPrice())&&"1".equals(frontCourseVo.getPrice())){
                wrapper.orderByDesc("price");
            }
            //一级类型排序
            if(!StringUtils.isEmpty(frontCourseVo.getSubjectParentId())){
                wrapper.eq("subject_parent_id",frontCourseVo.getSubjectParentId());
            }
            //二级类型排序
            if(!StringUtils.isEmpty(frontCourseVo.getSubjectId())){
                wrapper.eq("subject_id",frontCourseVo.getSubjectId());
            }
            //浏览数量关注度排序
            if(!StringUtils.isEmpty(frontCourseVo.getViewCount())&&"1".equals(frontCourseVo.getViewCount())){
                wrapper.orderByDesc("view_count");
            }

        }
        Page<EduCourse> page = new Page<>(curr,pagesize);
        IPage<EduCourse> iPage = this.page(page, wrapper);

        //得到数据
        List<EduCourse> records = page.getRecords();
        long total = page.getTotal();
        long size = page.getSize();
        long current = page.getCurrent();
        long pages = page.getPages();
        boolean previous = page.hasPrevious();
        boolean hasNext = page.hasNext();
        //填装数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("records",records);
        map.put("total",total);
        map.put("size",size);
        map.put("current",current);
        map.put("pages",pages);
        map.put("previous",previous);
        map.put("hasNext",hasNext);
        return map;
    }
    //前端返回课程相关信息
    @Override
    public FrontCourseInfo getFrontCourseInformation(String courseid) {
        FrontCourseInfo frontCourseInformation = eduCourseMapper.getFrontCourseInformation(courseid);
        return frontCourseInformation;
    }


}
